// page/component/orders/orders.js
Page({
  data:{
    address: {},
    detail: '',
    hasAddress: false, 
    total: 0,
    orders: [],
    payList: {
      orderUser: null,                          
      orderPrice: null,                    
      orderUserName: "",               
      orderPhone: "",         
      orderAddress: "",   
      orderDetails: [
        {
          detailNum: null,                     
          detailPrice: null,                
          detailGoods: null                     
        }, {
          detailNum: null,
          detailPrice: null,
          detailGoods: null
        }
      ]
    },
    crease: 0.00,
    imgs: [],
    orderNum: null,
    userID: null,
    isSwitch: 1,
    deliverPrice: 0,
    totalPrice: 0
  },
  
  onLoad: function (query) {
    let num = query.num;
    this.setData({
      userID: getApp().globalData.userID
    })
    console.log(this.data.userID);
    let that = this;
    wx.getStorage({
      key: 'details',
      success(res) {    
        let data = JSON.parse(res.data);
        console.log(data.length);
        let j = 0;
        let list = []
        for (let i = 0; i < data.length; i++)
        {
          console.log(data[i])
          if (data[i] !== null) {
            console.log(j);
            list[j] = data[i];
            j++;
          }
        }
        that.setData({
          orders: list
        })
        console.log(that.data.orders);
      }
    });
    wx.getStorage({
      key: 'price',
      success(res) {
        that.setData({
          total: res.data,
          totalPrice: res.data
        })
      }
    });
    wx.getStorage({
      key: 'imgs',
      success(res) {
        let j = 0;
        let list = [];
        for (let i = 0; i < res.data.length; i++)
        {
          if (res.data[i] !== null) {
            list[j] = res.data[i];
            j++;
          }
        }
        that.setData({
          imgs: list
        })
      }
    })
    wx.getStorage({
      key: 'userID',
      success(res) {
        that.setData({
          userID: res.data
        }) 
      }
    });
    let userId = this.data.userID;
    if (userId == null) {  
      userId = getApp().globalData.userID
    } 
    wx.request({
      url: 'https://localhost:80/address/queryAllId/' + userId,
      header: {
        'content-type': 'application/json'
      },
      success (res) { 
        console.log(res.data);
        console.log('测试');
        if (typeof(num) === 'undefined') {
          if (res.data.length == 0) {
            that.setData({
              hasAddress: false
            })
          } else {
            let Detail = res.data[0].addrProvince + res.data[0].addrCity + res.data[0].addrArea + res.data[0].addrCommuity + res.data[0].addrDetail
            that.setData({
              address: res.data[0],
              detail: Detail,
              hasAddress: true
            })
          } 
        } else {
          let Detail = res.data[num].addrProvince + res.data[num].addrCity + res.data[num].addrArea + res.data[num].addrCommuity + res.data[num].addrDetail
          that.setData({
            address: res.data[num],
            detail: Detail,
            hasAddress: true
          })
        }     
      }
    });
  },

  /**
   * 计算总价
   */

  toPay() {
    console.log(this.data.total); 
    console.log(this.data.address.addrNickname);
    console.log(this.data.address.addrPhone);
    console.log('ok');
    console.log(this.data.address.addrDid);
    console.log('ok');
    console.log(this.data.detail);
    console.log(this.data.orders);
    console.log(this.data.isSwitch);
    let storage = null;
    wx.getStorage({
      key: 'userID',
      success(res) {
        storage = res.data;
        console.log(storage);
      }
    });
    let that = this;
    if (typeof(this.data.address.addrNickname) == 'undefined') {
      wx.showModal({
        title: '温情提示',
        content: '亲，请先填写地址，再购买',
        text:'center',
        complete() {}
      });
    } else {
      let userId = that.data.userID;
      if (that.data.userID == null) {
        userId = storage;
      } 
      console.log(userId);
      let detail = '配送地址：' + that.data.detail
      wx.showModal({
        title: '确认配送地址',
        content: detail,
        success(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              let detail = that.data.detail + '/' + that.data.address.addrDid;
              let allPrice = 0;
              for (let i = 0; i < that.data.orders.length; i++)
              {
                allPrice += JSON.parse(that.data.orders[i].detailPrice);
              }
              console.log(allPrice);
              if (that.data.isSwitch == 2) {
                allPrice = allPrice + 2
              }
              allPrice = allPrice.toFixed(2);
              console.log(allPrice);
              console.log(that.data.orders);
              wx.request({
                url: 'https://localhost:80/order/create',
                header: {
                  'content-type': 'application/json;charset=UTF-8'
                },
                data: { 
                  orderUser: userId,                         
                  orderPrice: allPrice,                   
                  orderUserName: that.data.address.addrNickname,                
                  orderPhone: that.data.address.addrPhone,            
                  orderAddress: detail, 
                  orderDetails: that.data.orders,
                  orderDispatchType: that.data.isSwitch
                },    
                method: 'post',
                success (res) {
                  console.log(res.data);
                  that.setData({
                    orderNum: res.data.orderId
                    // orderNum: res.data
                  });
                  console.log('ok');
                  console.log(res.data.orderId);
                  console.log(res.data.hashCode)
                  console.log('ok');
                  console.log(userId);
                  console.log(allPrice);
                  console.log(getApp().globalData.code);
                  wx.request({
                    url: 'https://localhost:80/wcpay/pay',
                    data: {
                      id: userId,
                      name: '测试商品',
                      // 订单编号
                      // orderNum: that.data.orderNum,
                      orderNum: res.data.orderId,
                      hashcode: res.data.hashCode,
                      price: allPrice,
                      code: getApp().globalData.code
                    },
                    header: {
                      'content-type': 'application/json' //默认值
                    },
                    method: 'post',
                    success: function (res) {
                      console.log(res.data);
                      console.log(that.data.address.addrDid);
                      // 发起支付
                      wx.requestPayment({
                        timeStamp: res.data.timeStamp,
                        nonceStr: res.data.nonceStr,
                        package: res.data.package,
                        signType: 'MD5',
                        paySign: res.data.paySign,
                        success (res) {
                          console.log('--------------------------');
                          console.log(res);
                          wx.navigateTo({
                            url: '../paysuccess/paysuccess'
                          })
                          console.log('--------------------------');
                        },
                        fail (res) {
                          console.log(res);
                          let numUrl = '../payfail/payfail';  
                          wx.navigateTo({
                            url: numUrl
                          })
                        }
                      })
                    }
                  });
                },
                fail (res) {
                  console.log(res);
                  let numUrl = '../payfail/payfail';  
                  wx.navigateTo({
                    url: numUrl
                  })
                }
              });
            } else if (res.cancel) {
                console.log('用户点击取消');
            }
        }
      }) 
    }
  },
  
  address () {
    wx.navigateTo({
      url: '../address/address'
    })
  },

  takeaddress () {
    wx.navigateTo({
      url: '../takeaddress/takeaddress'
    })    
  }, 

  discount () {
    // wx.navigateTo({
    //   url: '../discount/discount'
    // })
    wx.showModal({
      title: '友情提示',
      content: '暂无此功能，敬请期待',
      text:'center',
      complete() {}
    });
  },

  return () {
    console.log('456');
    wx.switchTab({
      url: '../cart/cart'
    })
  },

  onUnload: function () {
    wx.reLaunch({
      url: '../cart/cart'
    })
  },

  switchChange (query) {
    console.log(query);
    let total = this.data.total;
    if (query.detail.value) {
      total = parseFloat(total);
      total = total + 2;
      console.log(total);
      total = total.toFixed(2);
      console.log(total);
      this.setData({
        isSwitch: 2,
        deliverPrice: 2,
        totalPrice: total
      });
      wx.showToast({
        title: '确认配送',
        icon: 'success',
        duration: 1000
      })
    } else {
      this.setData({
        isSwitch: 1,
        deliverPrice: 0,
        totalPrice: total,
      });
      wx.showToast({
        title: '取消配送成功',
        icon: 'none',
        duration: 1000
      })
    }
  }
})

